import { _decorator, Component, EditBox, Label, Node } from 'cc';
import { UserInfo } from '../common/UserInfo';
import { buildingType } from '../settings/const';
import { UIManager } from '../common/UIManager';
import { PrefabEnum } from '../common/PrefabEnum';
import { BuildingUpGrade } from '../village/BuildingUpGrade';
import { BManager } from '../entity/BManager';
import { Building } from '../entity/Buildings';
import AllyApi from '../api/AllyApi';
import { AllyOperateType } from '../entity/Ally';
import { BuildingDetail } from '../village/BuildingDetail';
const { ccclass, property } = _decorator;

@ccclass('CreateAlly')
export class CreateAlly extends Component {

    @property(Node)
    limit: Node
    @property(Node)
    content: Node

    @property(Label)
    level: Label
    @property(Node)
    upgrade: Node
    @property(Label)
    allyName:Label

    @property(Node)
    createBtn: Node

    start() {
        let bm = BManager.getBManageById(buildingType.B18_Embassy)
        if (bm && bm.grade >= 3) {
            this.limit.active = false
            this.content.active = true
        } else {
           
            this.limit.active = true
            this.content.active = false
        }

        if(bm){
            this.level.string = '当前使节馆等级' + bm.grade
        } else {
            this.level.string = '当前还没有建造使节馆'
            this.upgrade.getChildByName('Label').getComponent(Label).string = '去建造使节馆'
        }
        
        this.allyName.string = UserInfo.instance.villageData.user.uInfo.name + '的联盟'
        this.upgrade.on(Node.EventType.TOUCH_END, this.onUpgrade, this)
        this.createBtn.on(Node.EventType.TOUCH_END, this.onCreate, this)

    }

    async onUpgrade() {

        let bm = BManager.getBManageById(buildingType.B18_Embassy)
        if(bm){
            let building = Building.createBuildingByBManager(bm)

            let ui = await UIManager.instance.openUI(PrefabEnum.BuildingUpGrade)
            ui.getComponent(BuildingUpGrade).setData(building)
        } else {
            let building = Building.createByIdAndLevel(buildingType.B18_Embassy, 1)
            let ui = await UIManager.instance.openUI(PrefabEnum.BuildingDetail)
            ui.getComponent(BuildingDetail).setData(building)
        }

        

        UIManager.instance.closeUI(PrefabEnum.AllyIndex)
    }

    async onCreate() {
        await UIManager.instance.showLoading()
        let res = await AllyApi.Execute({
            op: AllyOperateType.Create,
        })

        UIManager.instance.closeLoading()
        console.log(res)

        let name = UserInfo.instance.villageData.user.uInfo.name
        await UIManager.instance.confrim({
            title: '提示',
            content: `恭喜，${name}的联盟已经创建成功，现在就进入联盟邀请好友加入吧！`,
            isShowCancel:false,
            confrimText : '进入联盟'
        })

        UIManager.instance.closeUI(PrefabEnum.AllyIndex)
        UIManager.instance.openUI(PrefabEnum.AllyIndex)
    }
}


